import Vue from 'vue'
import Vuex from 'vuex'
import _ from 'lodash'
import getters from './getters'

Vue.use(Vuex)

const modulesFiles = require.context('./modules', true, /\.js$/)
const _initState = {}

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  _initState[moduleName] = _.cloneDeep(value.default.state)

  return modules
}, {})
console.log(_initState)
const store = new Vuex.Store({
  state: {
    _initState,
  },
  modules,
  getters,
  mutations: {
    // 定义全局的清理方法
    RESET_ALL_STATE(state) {
      const initState = _.cloneDeep(state._initState)
      Object.keys(state).forEach((item) => {
        if (item !== '_initState') {
          state[item] = initState[item]
        }
      })
    },
  },
})

export default store
